<script setup lang="ts">
import { ref } from 'vue'
import { REGEX_MOBILE } from '@/libs/validate'
import SliderCaptcha from '@/components/slide-captcha/SliderCaptcha.vue'
import { doGetStoreInfoByShopAssistantPhone } from '@/apis/home'
import QCountDown from '@/components/q-count-down/q-count-down.vue'
import { useUserStore } from '@/store/modules/user'
import { useStoreInfoStore } from '@/store/modules/storeInfo'
import { doPostSmsCode, doSignByUser } from '@/apis/sign/index'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { GrantType } from '@/apis/sign/type'

onLoad(() => {
  uni.$emit('updateTitle')
})
const tel = ref('')
const code = ref('')
const countDownRef = ref()
const countDown = ref(66000)
const hasCountDown = ref(false)
const showSliderCaptcha = ref(false)
const $userStore = useUserStore()
const $useStoreInfoStore = useStoreInfoStore()
// 判断登录方式状态
const codetype = ref(true)
const codeRegex = /^\d{4}$/
const passwordIcon = ref('')
const isPassword = ref(false)

onShow(() => {
  if (!$userStore.token) return
  uni.reLaunch({ url: '/pages/home/Index' })
})

const getCodeHandle = async () => {
  if (!REGEX_MOBILE(tel.value)) {
    uni.showToast({
      title: '请输入正确手机号',
	  icon: 'none',
    })
    return
  }
  showSliderCaptcha.value = true
}
const countFinishHandle = () => {
  hasCountDown.value = false
  countDownRef.value.reset()
}
const success = (e: { data: string }) => {
  hasCountDown.value = true
  countDownRef.value.start()
  showSliderCaptcha.value = false
  code.value = e.data
}
const handleSign = async () => {
  if (!tel.value || !REGEX_MOBILE(tel.value))
    return uni.showToast({
      title: '请输入正确手机号',
      icon: 'none',
    })
	
	if(codetype.value){
		  const codeData = code.value
		  if (!codeData || !codeRegex.test(codeData)) {
		    uni.showToast({
		      title: '请输入正确的验证码',
		      icon: 'none',
		      duration: 1000,
		    })
		    return
		  }
	}
	
	
  const grantType = codetype.value ? GrantType.SMS_CODE : GrantType.PASSWORD	
  const params = codetype.value
   ? {
       mobile: tel.value,
       code: code.value,
     }
   : {
       username: tel.value,
       password: code.value,
     }
 
  const {
    data,
    code: staus,
    msg,
  } = await doSignByUser(grantType, params)
  console.log('staus', staus)
  if (staus === 20) {
    uni.showToast({
      title: '验证码已失效或用户不是店员',
      icon: 'none',
    })
    return
  }
  if (staus !== 200 || !data) {
    return uni.showToast({
      title: `${msg ? msg : '登录失败'}`,
      icon: 'none',
    })
  }
  const { value: access_token, refreshToken } = data
  $userStore.ADD_TOKEN({ access_token, refresh_token: refreshToken.value, shopAssistantPhone: tel.value })
  uni.reLaunch({ url: '/pages/home/Index' })
}
async function initStoreInfo() {
	if (!tel.value) return
  const { code, data, msg } = await doGetStoreInfoByShopAssistantPhone(tel.value)
  if (code !== 200)
    return uni.showToast({
      title: `${msg ? msg : '请求错误'}`,
      icon: 'none',
    })
  $useStoreInfoStore.SET_STORE_INFO(data)
}

const canclelogin =()=>{
	uni.reLaunch({ url: '/pages/home/Index' })
}
/**
 *  点击切换登录方式函数
 */
const handleChangeCode = (): void => {
  // // 切换登录方式并且 通过codetype切换图标显示的内容
  codetype.value = !codetype.value
  passwordIcon.value = codetype.value ? '' : 'eye'
  isPassword.value = !codetype.value
  // // 切换登录方式后清空输入框的内容
  code.value = ''
  tel.value = ''
}
/**
 * 改变密码框的状态和图标的函数
 */
const handlerChangeIcon = (): void => {
  // 改变密码框的状态
  isPassword.value = !isPassword.value
  // 改变密码框的图标
  passwordIcon.value = isPassword.value ? 'eye' : 'eye-fill'
}
</script>

<template>
  <view class="sign">
    <image class="sign__img" src="https://oss.yuanshiquan.top/img/2025/7/2368809ba06d262e210aef5543.png" />
    <view class="sign__input">
      <u-field v-model="tel" label="手机号" maxlength="11" style="color: #999999" @blur="initStoreInfo"> </u-field>
      <view class="sign__input-compose">
		<u-field
		  :label="codetype ?'验证码':'密码'"
		  v-model="code"
		  :border-bottom="false"
		  :maxlength="codetype ? '6' : '20'"
		  :password="isPassword"
		  :placeholder="codetype ? '请填写验证码' : '请填写密码'"
		  :right-icon="passwordIcon"
		  trim
		  style="color: #999999" :border="false"
		  @right-icon-click="handlerChangeIcon"
		></u-field>
		<template v-if="codetype">
			<view v-show="!hasCountDown" class="sign__input-compose--btn" @click="getCodeHandle">获取验证码</view>
			<q-count-down v-show="hasCountDown" ref="countDownRef" :timestamp="countDown" format="mm:ss" @end="countFinishHandle" />
		</template>
      </view>
    </view>
    <u-button class="sign__but" type="primary" shape="circle" @click="handleSign">登录</u-button>
	<view class="type_login"><text @click="handleChangeCode">{{codetype ? '密码登录' : '验证码登录'}}</text></view>
	<view class="cancle_login"><text @click="canclelogin">取消登录</text></view>
  </view>
  <slider-captcha v-model="showSliderCaptcha" :get-form="() => tel" sms-type="LOGIN" :do-submit="doPostSmsCode" :scale="2" @success="success" />
</template>

<style lang="scss" scoped>
page {
  background: #fff;
}
@include b(sign) {
  @include e(img) {
    display: block;
    margin: 0 auto;
    width: 228rpx;
    height: 82rpx;
    margin-top: 156rpx;
  }
  @include e(input) {
    margin: 0 auto;
    margin-top: 64rpx;
    border-radius: 10rpx;
    border: 1px solid #f3f3f3;
    width: 540rpx;
  }
  @include e(input-compose) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f3f3f3;
    @include m(btn) {
      font-size: 26rpx;
      color: #409eff;
      width: 210rpx;
    }
  }
  @include e(but) {
    margin: 0 auto;
    margin-top: 298rpx;
    width:80%;
    line-height: 88rpx;
    text-align: center;
    color: #fff;
    height: 88rpx;
    border-radius: 92rpx;
	display: block;
  }
}
.cancle_login {
	text-align: center;
	margin-top: 30rpx;
}
.type_login {
	text-align: center;
	margin: 30rpx 0 50rpx;
	color:#2979ff;
	font-size: 32rpx;
}
</style>
